package com.streamer.app

import android.app.Dialog
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.button.MaterialButton
import com.streamer.app.R
import com.streamer.app.adapter.CouponSelectionAdapter
import com.streamer.app.adapter.CouponRecordAdapter
import com.streamer.app.bean.CouponBean
import com.streamer.app.utils.api.ViewModel

class CouponActivity : BaseActivity() {
    private lateinit var clTopBar: ConstraintLayout
    private lateinit var tvTabSend: TextView
    private lateinit var tvTabRecord: TextView
    private lateinit var viewTabIndicator: View
    private lateinit var btnPublish: MaterialButton
    private lateinit var layoutSend: View
    private lateinit var layoutRecord: View
    private var mRoomId = ""
    private var mStopPush = false
    private var viewMode = ViewModel()

    // 优惠券选择相关
    private var couponSelectionDialog: Dialog? = null
    private var couponSelectionAdapter: CouponSelectionAdapter? = null
    private var selectedCoupon: CouponBean? = null
    private var currentPage = 1
    private var pageSize = 10

    // 优惠券记录相关
    private lateinit var rvCouponRecords: RecyclerView
    private lateinit var layoutEmptyRecords: View
    private lateinit var layoutEmptyTopNameRecords: View
    private lateinit var couponPublishTime: View
    private lateinit var couponPublishTimerLabel: View
    private lateinit var couponCountLabel: View
    private lateinit var couponName: View
    private lateinit var tvCouponNameValue: TextView
    private lateinit var tvCouponType: TextView
    private lateinit var tvCouponCountStock: TextView
    private lateinit var etPublishDuration: EditText
    private lateinit var etPublishTimerMin: EditText
    private lateinit var etPublishTimerSec: EditText
    private lateinit var etCouponCount: EditText
    private var couponRecordAdapter: CouponRecordAdapter? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_coupon)
        initViews()
        setupTopPadding()
        setupTab()
    }

    private fun initViews() {
        mRoomId = intent.getStringExtra("roomId").toString()

        tvCouponNameValue = findViewById<TextView>(R.id.tv_coupon_name_value)
        tvCouponType = findViewById<TextView>(R.id.tv_coupon_type_value)
        tvCouponCountStock = findViewById<TextView>(R.id.tv_coupon_count_stock)

        // 2. 获取输入数据
        etPublishDuration = findViewById<EditText>(R.id.et_publish_duration)
        etPublishTimerMin = findViewById<EditText>(R.id.et_publish_timer_min)
        etPublishTimerSec = findViewById<EditText>(R.id.et_publish_timer_sec)
        etCouponCount = findViewById<EditText>(R.id.et_coupon_count)

        couponPublishTime = findViewById(R.id.coupon_publish_time)
        couponPublishTimerLabel = findViewById(R.id.coupon_publish_timer_label)
        couponName = findViewById(R.id.coupon_name)
        couponCountLabel = findViewById(R.id.coupon_count_label)
        clTopBar = findViewById(R.id.cl_top_bar)
        tvTabSend = findViewById(R.id.tv_tab_send)
        tvTabRecord = findViewById(R.id.tv_tab_record)
        viewTabIndicator = findViewById(R.id.view_tab_indicator)
        layoutSend = findViewById(R.id.layout_send)
        layoutRecord = findViewById(R.id.layout_record)
        btnPublish = findViewById(R.id.btn_publish)
        findViewById<View>(R.id.iv_back).setOnClickListener { finish() }

        // 设置优惠券名称卡片点击事件
        findViewById<View>(R.id.card_coupon_name).setOnClickListener {
            showCouponSelectionDialog()
        }

        // 设置发布按钮点击事件
        btnPublish.setOnClickListener {
            if (mStopPush) {
                viewMode.stop(selectedCoupon?.id.toString())
            } else {
                publishCoupon()

            }
        }
        viewMode.stopStateLv.observe(this@CouponActivity) {
            mStopPush = false
            clearForm(false)
        }

        // 初始化优惠券记录RecyclerView
        initCouponRecordRecyclerView()
    }

    private fun initCouponRecordRecyclerView() {
        rvCouponRecords = findViewById(R.id.rv_coupon_records)
        layoutEmptyRecords = findViewById(R.id.layout_empty_records)
        layoutEmptyTopNameRecords = findViewById(R.id.layout_table_header)

        rvCouponRecords.layoutManager = LinearLayoutManager(this)
        couponRecordAdapter = CouponRecordAdapter(mutableListOf())
        rvCouponRecords.adapter = couponRecordAdapter
    }

    private fun setupTopPadding() {
        ViewCompat.setOnApplyWindowInsetsListener(clTopBar) { view, insets ->
            val statusBarHeight = insets.getInsets(WindowInsetsCompat.Type.statusBars()).top
            view.setPadding(
                view.paddingLeft, statusBarHeight, view.paddingRight, view.paddingBottom
            )
            insets
        }
    }

    private fun setupTab() {
        tvTabSend.setOnClickListener {
            // 更新Tab样式
            tvTabSend.setTextColor(getColor(R.color.black))
            tvTabSend.setTypeface(null, android.graphics.Typeface.BOLD)
            tvTabRecord.setTextColor(getColor(R.color.gray))
            tvTabRecord.setTypeface(null, android.graphics.Typeface.NORMAL)

            // 移动指示器到发放Tab
            moveIndicatorToTab(tvTabSend)

            // 切换内容
            layoutSend.visibility = View.VISIBLE
            layoutRecord.visibility = View.GONE
        }
        tvTabRecord.setOnClickListener {
            // 更新Tab样式
            tvTabSend.setTextColor(getColor(R.color.gray))
            tvTabSend.setTypeface(null, android.graphics.Typeface.NORMAL)
            tvTabRecord.setTextColor(getColor(R.color.black))
            tvTabRecord.setTypeface(null, android.graphics.Typeface.BOLD)

            // 移动指示器到记录Tab
            moveIndicatorToTab(tvTabRecord)

            // 切换内容
            layoutSend.visibility = View.GONE
            layoutRecord.visibility = View.VISIBLE

            // 加载优惠券记录数据
            loadCouponRecords()
        }
        // 默认选中发放tab
        tvTabSend.performClick()
    }

    private fun moveIndicatorToTab(targetTab: TextView) {
        // 更新指示器的约束
        val indicatorParams = viewTabIndicator.layoutParams as ConstraintLayout.LayoutParams
        indicatorParams.startToStart = targetTab.id
        indicatorParams.endToEnd = targetTab.id

        // 应用新的布局参数
        viewTabIndicator.layoutParams = indicatorParams
    }

    private fun showCouponSelectionDialog() {
        viewMode.couponList(mRoomId)
        if (couponSelectionDialog == null) {
            couponSelectionDialog = Dialog(this)
            couponSelectionDialog?.setContentView(R.layout.dialog_coupon_selection)
            couponSelectionDialog?.window?.setLayout(
                android.view.ViewGroup.LayoutParams.MATCH_PARENT,
                android.view.ViewGroup.LayoutParams.WRAP_CONTENT
            )

            setupCouponSelectionDialog()
        }

        // 加载优惠券数据
        loadCouponData()
        couponSelectionDialog?.show()
    }

    private fun setupCouponSelectionDialog() {
        val dialog = couponSelectionDialog ?: return

        // 初始化RecyclerView
        val rvCouponList = dialog.findViewById<RecyclerView>(R.id.rv_coupon_list)
        rvCouponList.layoutManager = LinearLayoutManager(this)

        // 初始化适配器
        couponSelectionAdapter = CouponSelectionAdapter(mutableListOf()) { coupon ->
            selectedCoupon = coupon
        }
        rvCouponList.adapter = couponSelectionAdapter

        // 搜索功能
        val etSearch = dialog.findViewById<EditText>(R.id.et_search_coupon)
        etSearch.setOnEditorActionListener { _, _, _ ->
            val query = etSearch.text.toString().trim()
            couponSelectionAdapter?.filterCoupons(query)
            true
        }

        // 取消按钮
        dialog.findViewById<TextView>(R.id.tv_cancel).setOnClickListener {
            couponSelectionDialog?.dismiss()
        }

        // 确定按钮
        dialog.findViewById<TextView>(R.id.tv_confirm).setOnClickListener {
            val selected = couponSelectionAdapter?.getSelectedCoupon()
            if (selected != null) {
                selectedCoupon = selected
                updateCouponNameDisplay(selected)


                couponSelectionDialog?.dismiss()
            } else {
                Toast.makeText(this, "请选择一个优惠券", Toast.LENGTH_SHORT).show()
            }
        }
    }

    private fun loadCouponData() {
        viewMode.CouponLV.observe(this@CouponActivity) {
            it?.rows?.let { it1 -> couponSelectionAdapter?.updateData(it1) }

        }

    }

    private fun updateCouponNameDisplay(couponName: CouponBean) {
        // 更新优惠券名称显示

        tvCouponNameValue.text = couponName.couponName

        if (couponName.couponType == "1") {
            tvCouponType.text = "满减卷"
        } else if (couponName.couponType == "2") {
            tvCouponType.text = "折扣卷"
        }
        if (couponName.isLimited == 0) {
            tvCouponCountStock.text = "库存剩余：不限"

        } else {
            tvCouponCountStock.text = "库存剩余：${couponName.remainingNum}张"

        }
        tvCouponNameValue.setTextColor(getColor(R.color.black))
    }

    private fun publishCoupon() {
        // 1. 验证是否选中优惠券
        if (selectedCoupon == null) {
            Toast.makeText(this, "请先选择优惠券", Toast.LENGTH_SHORT).show()
            return
        }


        val publishDuration = etPublishDuration.text.toString().trim()
        val publishTimerMin = etPublishTimerMin.text.toString().trim()
        val publishTimerSec = etPublishTimerSec.text.toString().trim()
        val couponCount = etCouponCount.text.toString().trim()

        // 3. 验证输入数据
        if (publishDuration.isEmpty()) {
            Toast.makeText(this, "请输入发布时间", Toast.LENGTH_SHORT).show()
            etPublishDuration.requestFocus()
            return
        }

        if (publishTimerMin.isEmpty() && publishTimerSec.isEmpty()) {
            Toast.makeText(this, "请输入发布倒计时时间", Toast.LENGTH_SHORT).show()
            if (publishTimerMin.isEmpty()) {
                etPublishTimerMin.requestFocus()
            } else {
                etPublishTimerSec.requestFocus()
            }
            return
        }

        if (couponCount.isEmpty()) {
            Toast.makeText(this, "请输入优惠券数量", Toast.LENGTH_SHORT).show()
            etCouponCount.requestFocus()
            return
        }

        // 4. 验证数据有效性
        val duration = publishDuration.toIntOrNull()
        val min = publishTimerMin.toIntOrNull() ?: 0
        val sec = publishTimerSec.toIntOrNull() ?: 0
        val count = couponCount.toIntOrNull()

        if (duration == null || duration <= 0) {
            Toast.makeText(this, "发布时间必须大于0", Toast.LENGTH_SHORT).show()
            etPublishDuration.requestFocus()
            return
        }

        if (min < 0 || sec < 0 || (min == 0 && sec == 0)) {
            Toast.makeText(this, "发布倒计时时间无效", Toast.LENGTH_SHORT).show()
            if (min < 0) {
                etPublishTimerMin.requestFocus()
            } else {
                etPublishTimerSec.requestFocus()
            }
            return
        }

        if (count == null || count <= 0) {
            Toast.makeText(this, "优惠券数量必须大于0", Toast.LENGTH_SHORT).show()
            etCouponCount.requestFocus()
            return
        }

        if (selectedCoupon?.isLimited != 0) {
            // 5. 验证库存
            if (count > selectedCoupon!!.remainingNum) {
                Toast.makeText(this, "优惠券数量不能超过库存剩余数量", Toast.LENGTH_SHORT).show()
                etCouponCount.requestFocus()
                return
            }
        }


        // 6. 计算总秒数
        val totalSeconds = min * 60 + sec

        // 7. 调用发布接口
        publishCouponToServer(
            couponId = selectedCoupon!!.id,
            publishDuration = duration,
            publishTimer = totalSeconds,
            couponCount = count,
        )
    }

    private fun publishCouponToServer(
        couponId: String,
        publishDuration: Int,
        publishTimer: Int,
        couponCount: Int,
    ) {
        // 显示加载状态
        btnPublish.isEnabled = false

        // 调用API发布优惠券
        viewMode.publishCoupon(
            mRoomId, couponId, publishTimer, couponCount, publishDuration * 60
        )

        // 观察发布结果
        viewMode.PublishCouponLV.observe(this) { result ->
            btnPublish.isEnabled = true

            if (result != null) {
                Toast.makeText(this, "优惠券发布成功", Toast.LENGTH_SHORT).show()
                // 发布成功后可以清空表单或跳转到记录页面
                clearForm()
                // 切换到记录tab
//                tvTabRecord.performClick()
            }
        }
    }

    private fun clearForm(stats: Boolean = true) {
        // 清空表单数据
//        selectedCoupon = null
        if (stats) {
            couponName.setBackgroundColor(getColor(R.color.prohibit))

            couponPublishTime.setBackgroundColor(getColor(R.color.prohibit))


            couponPublishTimerLabel.setBackgroundColor(getColor(R.color.prohibit))
            couponCountLabel.setBackgroundColor(getColor(R.color.prohibit))
            etPublishDuration.isEnabled = false
            etPublishTimerMin.isEnabled = false
            etPublishTimerSec.isEnabled = false
            etCouponCount.isEnabled = false
            mStopPush = true
            btnPublish.apply {
                text = "停止发放"
                val colorStateList =
                    ContextCompat.getColorStateList(this@CouponActivity, R.color.red)
                btnPublish.backgroundTintList = colorStateList
            }
        } else {
            couponName.setBackgroundResource(R.drawable.view_f4f8fe_bg)

            couponPublishTime.setBackgroundResource(R.drawable.view_f4f8fe_bg)


            couponPublishTimerLabel.setBackgroundResource(R.drawable.view_f4f8fe_bg)
            couponCountLabel.setBackgroundResource(R.drawable.view_f4f8fe_bg)
            etPublishDuration.isEnabled = true
            etPublishTimerMin.isEnabled = true
            etPublishTimerSec.isEnabled = true
            etCouponCount.isEnabled = true
            mStopPush = false
            btnPublish.apply {
                text = "立即发布"
                val colorStateList =
                    ContextCompat.getColorStateList(this@CouponActivity, R.color.red)
                btnPublish.backgroundTintList = colorStateList
            }
        }

    }


    private fun loadCouponRecords() {
        // 调用API获取优惠券记录数据
        viewMode.couponPushList(mRoomId, pageSize, currentPage)

        // 观察API返回的数据
        viewMode.CouponListLV.observe(this@CouponActivity) { result ->
            if (result != null && result.rows != null) {
                Log.d("CouponRecords", "API返回优惠券记录: ${result.rows.size} 条")
                updateCouponRecords(result.rows)
            } else {
                Log.d("CouponRecords", "API返回优惠券记录为空")
                updateCouponRecords(emptyList())
            }
        }
    }

    private fun updateCouponRecords(records: List<CouponBean>) {
        if (records.isEmpty()) {
            // 显示空状态
            layoutEmptyRecords.visibility = View.VISIBLE
            layoutEmptyTopNameRecords.visibility = View.GONE
            rvCouponRecords.visibility = View.GONE
        } else {
            // 显示记录列表
            layoutEmptyRecords.visibility = View.GONE
            rvCouponRecords.visibility = View.VISIBLE
            layoutEmptyTopNameRecords.visibility = View.VISIBLE


            // 更新适配器数据
            couponRecordAdapter?.updateRecords(records)
        }
    }
} 